#!/bin/bash

# 学生选课系统手动部署脚本
set -e

echo "🚀 开始部署学生选课系统到服务器..."

# 服务器配置
SERVER_IP="166.88.182.218"
SERVER_USER="root"
PROJECT_NAME="student-course-system"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 第一步：准备部署包
print_info "📦 准备部署包..."

# 构建前端
print_info "构建前端..."
cd client
npm install
npm run build
cd ..

# 创建部署包目录
rm -rf deploy-temp
mkdir -p deploy-temp

# 复制文件
cp -r src deploy-temp/
cp -r client/dist deploy-temp/public
cp package*.json deploy-temp/
cp database.sqlite deploy-temp/
cp Dockerfile.simple deploy-temp/
cp docker-compose.simple.yml deploy-temp/
cp .env.example deploy-temp/.env

# 创建压缩包
tar -czf ${PROJECT_NAME}.tar.gz deploy-temp/

print_info "✅ 部署包准备完成"

# 第二步：上传到服务器
print_info "📤 上传项目到服务器..."
print_warning "请输入服务器密码: G4QiH1cM3qAh6P5"

# 上传文件
scp -o StrictHostKeyChecking=no ${PROJECT_NAME}.tar.gz ${SERVER_USER}@${SERVER_IP}:/tmp/

print_info "✅ 上传完成"

# 第三步：创建服务器部署脚本
print_info "📝 创建服务器部署脚本..."

cat > server-deploy.sh << 'EOF'
#!/bin/bash
echo "🔄 开始服务器部署..."

PROJECT_NAME="student-course-system"
DEPLOY_PATH="/opt/${PROJECT_NAME}"

# 安装 Docker
if ! command -v docker &> /dev/null; then
    echo "安装 Docker..."
    curl -fsSL https://get.docker.com | sh
    systemctl enable docker
    systemctl start docker
fi

# 安装 Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo "安装 Docker Compose..."
    curl -L "https://github.com/docker/compose/releases/download/v2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi

# 停止现有服务
if [ -d "${DEPLOY_PATH}" ]; then
    cd ${DEPLOY_PATH}
    if [ -f docker-compose.simple.yml ]; then
        echo "停止现有服务..."
        docker-compose -f docker-compose.simple.yml down
    fi
fi

# 创建部署目录
mkdir -p ${DEPLOY_PATH}
cd ${DEPLOY_PATH}

# 解压新代码
tar -xzf /tmp/${PROJECT_NAME}.tar.gz --strip-components=1

# 创建数据目录
mkdir -p data logs

# 构建并启动服务
echo "构建并启动服务..."
docker-compose -f docker-compose.simple.yml up --build -d

# 等待服务启动
echo "等待服务启动..."
sleep 30

# 检查容器状态
echo "检查服务状态..."
docker-compose -f docker-compose.simple.yml ps

# 检查服务健康
for i in {1..10}; do
    if curl -f http://localhost/health > /dev/null 2>&1; then
        echo "✅ 服务健康检查通过"
        break
    else
        echo "⏳ 等待服务启动... ($i/10)"
        sleep 5
    fi
done

# 清理
rm -f /tmp/${PROJECT_NAME}.tar.gz

echo "🎉 服务器部署完成！"
echo "🌐 访问地址: http://$(curl -s ifconfig.me || hostname -I | awk '{print $1}')"
echo "👤 测试账户:"
echo "   管理员: admin / admin123"
echo "   教师: teacher1 / teacher123"
echo "   学生: student1 / student123"
EOF

# 上传部署脚本
print_info "📤 上传部署脚本到服务器..."
print_warning "请再次输入服务器密码: G4QiH1cM3qAh6P5"

scp -o StrictHostKeyChecking=no server-deploy.sh ${SERVER_USER}@${SERVER_IP}:/tmp/

# 第四步：执行服务器部署
print_info "🔧 连接服务器执行部署..."
print_warning "请第三次输入服务器密码: G4QiH1cM3qAh6P5"

ssh -o StrictHostKeyChecking=no ${SERVER_USER}@${SERVER_IP} "chmod +x /tmp/server-deploy.sh && /tmp/server-deploy.sh"

# 第五步：验证部署
print_info "🔍 验证部署..."

sleep 10

if curl -f "http://${SERVER_IP}/health" > /dev/null 2>&1; then
    print_info "✅ 部署成功！"
    print_info "🌐 访问地址: http://${SERVER_IP}"
    print_info "👤 测试账户:"
    print_info "   管理员: admin / admin123"
    print_info "   教师: teacher1 / teacher123"
    print_info "   学生: student1 / student123"
else
    print_warning "⚠️  服务可能还在启动中，请稍后访问: http://${SERVER_IP}"
fi

# 清理本地文件
print_info "🧹 清理临时文件..."
rm -rf deploy-temp ${PROJECT_NAME}.tar.gz server-deploy.sh

print_info "🎉 部署完成！"

echo ""
echo "==============================================="
echo "🎯 部署信息总结"
echo "==============================================="
echo "🌐 访问地址: http://${SERVER_IP}"
echo "👤 测试账户:"
echo "   管理员: admin / admin123"
echo "   教师: teacher1 / teacher123"  
echo "   学生: student1 / student123"
echo "===============================================" 